package club.web51.classroominteractiontoolsadmin.Services;

import club.web51.classroominteractiontoolsadmin.DO.MainDO.Course;
import club.web51.classroominteractiontoolsadmin.DO.MainDO.Section;
import club.web51.classroominteractiontoolsadmin.DO.MainDO.User;
import club.web51.classroominteractiontoolsadmin.DO.RelationDO.Section_User;
import club.web51.classroominteractiontoolsadmin.Repositories.CourseRepository;
import club.web51.classroominteractiontoolsadmin.Repositories.SectionRepository;
import club.web51.classroominteractiontoolsadmin.Repositories.Section_UserRepository;
import club.web51.classroominteractiontoolsadmin.Repositories.UserRepository;
import club.web51.classroominteractiontoolsadmin.Utils.SFWhere;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @Classname StudentService
 * @Description TODO
 * @Date 2020/11/14 0:11
 * @Created by wlh
 */
@Service
public class StudentService {
    @Resource
    UserRepository userRepository;
    @Resource
    Section_UserRepository section_userRepository;
    @Resource
    CourseRepository courseRepository;
    @Resource
    SectionRepository sectionRepository;


    /**
     * 通过学生ID查找课程
     * @param uid
     * @param pageable
     * @return
     */
    public Page<Course> findCourseByUid(Long uid,Pageable pageable){
        User user = userRepository.getOne(uid);
        Section_User section_user = Section_User.builder().uid(uid).build();
        //筛选出所有学生的群组、课程记录
        List<Section_User> section_users = section_userRepository.findAll(SFWhere.and(section_user).build());
        //筛选出所有不重复的课程ID记录
        List<Long> courseIdList = section_users.stream().map((Section_User::getCid)).collect(Collectors.toList());
        //根据课程列表ID筛选课程数据
        Page<Course> courses = courseRepository.findAll(SFWhere.and(Course.builder().build()).in(true,"cid",courseIdList).build(),pageable);
        return courses;
    }

    /**
     * 通过学生ID查找群组
     * @param uid
     * @param pageable
     * @return
     */
    public Page<Section> findSectionByUid(Long uid,Pageable pageable){
        User user = userRepository.getOne(uid);
        Section_User section_user = Section_User.builder().uid(uid).build();
        //筛选出所有学生的群组、课程记录
        List<Section_User> section_users = section_userRepository.findAll(SFWhere.and(section_user).build());
        //筛选出所有群组ID
        List<Long> sections = section_users.stream().map(Section_User::getSeid).collect(Collectors.toList());
        //筛选出所有群组
        Page<Section> sectionPage = sectionRepository.findAll(SFWhere.and(Section.builder().build()).in(true,"seid",sections).build(),pageable);
        return sectionPage;
    }
}
